<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :before-close="closeDlg"
    :close-on-click-modal="false"
    destroy-on-close="true"
    :width="width"
  >
    <div :style="'width: 100%; height: ' + height + ';'" class="scrollbar">
      <el-scrollbar style="height: 100%;">
        <el-table
          ref="dragTable"
          v-loading="listLoading"
          :data="list"
          row-key="ID"
          border
          fit
          highlight-current-row
          style="width: 100%;"
        >
          <!--    列表内容-->
<!--          <el-table-column v-if="pagePrivilege!==null" type="selection" width="40"></el-table-column>-->
<!--          <el-table-column v-if="pagePrivilege!==null" label="名称" width="" align="" show-overflow-tooltip>-->
<!--            <template slot-scope="{row}">-->
<!--              <span>{{ row.name }}</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="卫星" width="" align="" show-overflow-tooltip>
            <template slot-scope="{row}">
              <span>{{ row.satellite_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="星地距离(km)" width="75" align="" show-overflow-tooltip>
            <template slot-scope="{row}">
              <span>{{ row.distance }}</span>
            </template>
          </el-table-column>
          <el-table-column label="上行空间损耗" width="100" align="" show-overflow-tooltip>
            <template slot-scope="{row}">
              <span>{{ row.upSkyLoss }}</span>
            </template>
          </el-table-column>
          <el-table-column label="上行大气损耗修正值" width="85" align="" show-overflow-tooltip>
            <template slot-scope="{row}">
              <span>{{ row.upAtmosphereLoss }}</span>
            </template>
          </el-table-column>
          <el-table-column label="下行空间损耗" width="80" align="" show-overflow-tooltip>
            <template slot-scope="{row}">
              <span>{{ row.downSkyLoss }}</span>
            </template>
          </el-table-column>
          <el-table-column label="下行大气损耗修正值" width="85" align="" show-overflow-tooltip>
            <template slot-scope="{row}">
              <span>{{ row.dowmAtmosphereLoss }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.actions')" align="" width="80" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <!--                <el-button type="primary" size="mini" @click="handleUpdate(row)">-->
              <!--                  {{ $t('table.edit') }}-->
              <!--                </el-button>-->
<!--              <el-button size="mini" type="danger" @click="handleDelete(row)">-->
<!--                {{ $t('table.delete') }}-->
<!--              </el-button>-->
              <img
                @click="handleUpdate(row)"
                title="编辑"
                :src="listIcon.update"
                alt=""
                class="listIcon"
              />
              <img
                @click="handleDelete(row)"
                title="删除"
                :src="listIcon.delete"
                alt=""
                class="listIcon"
              />
            </template>
          </el-table-column>
<!--          <el-table-column align="center" label="Drag" width="80">-->
<!--            <template slot-scope="{}">-->
<!--              <svg-icon class="drag-handler" icon-class="drag" />-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table>
<!--        <div class="show-d">-->
<!--          <el-tag style="margin-right:12px;">{{ $t('table.dragTips1') }} :</el-tag> {{ oldList }}-->
<!--        </div>-->
<!--        <div class="show-d">-->
<!--          <el-tag>{{ $t('table.dragTips2') }} :</el-tag> {{ newList }}-->
<!--        </div>-->
      </el-scrollbar>
    </div>
    <!--    分页-->
<!--    <pagination v-show="total>0" :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageNumber" @pagination="getUserList" />-->

    <br><br>
    <span class="el-dialog__title">关联卫星</span>
    <div style="width: 100%; height: 200px; padding-top: 20px; margin-top: 30px; border: 1px solid #dfe6ec" class="scrollbar">
      <el-scrollbar style="height: 100%;">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="150px" style="margin-left:-20px;">
          <el-row>
            <el-col :span="12">
              <el-form-item label="卫星" prop="satelliteID">
                <el-select
                  v-model="temp.satelliteID"
                  class="filter-item"
                  style="width: 160px;"
                  placeholder="请选择卫星"
                  clearable
                  filterable
                  @click.native="LoadSatelliteList"
                >
                  <el-option v-for="item in satelliteList" :key="item.ID" :label="item.name" :value="item.ID" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="星地距离(km)" prop="distance">
                <el-input v-model="temp.distance" placeholder="星地距离(km)" style="width: 160px;">
                  <el-button slot="append" icon="" @click="countDistance">计算</el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="上行空间损耗" prop="upSkyLoss">
                <el-input-number v-model="temp.upSkyLoss" placeholder="上行空间损耗" :precision="2" :step="1" style="width: 160px;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上行大气损耗修正值" prop="upAtmosphereLoss">
                <el-input-number v-model="temp.upAtmosphereLoss" placeholder="上行大气损耗修正值" :precision="2" :step="1" style="width: 160px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="下行空间损耗" prop="downSkyLoss">
                <el-input-number v-model="temp.downSkyLoss" placeholder="下行空间损耗" :precision="2" :step="1" style="width: 160px;" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="下行大气损耗修正值" prop="dowmAtmosphereLoss">
                <el-input-number v-model="temp.dowmAtmosphereLoss" placeholder="下行大气损耗修正值" :precision="2" :step="1" style="width: 160px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <div style="float: right;margin-bottom: 10px;margin-right: 30px;">
<!--            <el-button @click="dialogFormVisible = false">-->
<!--              {{ $t('table.cancel') }}-->
<!--            </el-button>-->
            <el-button v-if="dialogStatus==='update'" type="" @click="handleCancel">
              取消
            </el-button>
            <el-button type="primary" @click="dialogStatus==='update'?updateData():createData()">
              {{ dialogStatus==='update' ? '编辑' : '创建' }}
            </el-button>
          </div>
        </el-form>
      </el-scrollbar>
    </div>
    <!--    对话框下方按钮-->
    <div slot="footer" class="dialog-footer">
      <!--    取消按钮-->
<!--      <el-button @click="closeDlg">-->
<!--        {{ $t('table.cancel') }}-->
<!--      </el-button>-->

      <!--    提交按钮-->
      <el-button type="primary" @click="closeDlg">
        关闭
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { isNotEmpty, zEnBase64 } from '@/utils'
import { getToken } from '@/utils/auth'
import global from '@/common'
import { getSatelliteList, getSentenceList, getStationSatelliteList } from '@/api/weixing/base'
import {
  batchSortStationSatellite,
  createStationSatellite,
  deleteStationSatellite, fetchStationSatelliteOne, getUserList, updateStationSatellite
} from '@/api/weixing/stationSatellite'
import Sortable from 'sortablejs'
import { fetchSatelliteOne } from '@/api/weixing/satellite'
import { doFormula } from '@/api/weixing/sentence'

export default {
  name: 'StationSatellite',
  props: {
    width: {
      type: String,
      default: '700px'
    },
    height: {
      type: String,
      default: '300px'
    },
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '卫星列表'
    },
    row: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      list: null, // 列表数据
      listLoading: true, // 列表状态为加载中
      loadingBtn: false, // 防止表单重复提交
      loadingBtnTitle: '确定', // 提交按钮标题
      dialogStatus: 'create',
      listIcon: global.listIcon, // 列表按钮图标
      satelliteList: [],
      distanceSentence: '',
      rules: {
        satelliteID: [{ required: true, message: '卫星不能为空', trigger: 'blur' }]
      },
      temp: {
        ID: '',
        applicationID: '',
        organizationID: '',
        stationID: '',
        satelliteID: '',
        name: '',
        orderSeq: 0,
        distance: '',
        upSkyLoss: '',
        upAtmosphereLoss: '',
        downSkyLoss: '',
        dowmAtmosphereLoss: ''
      },
      sortable: null,
      oldList: [],
      newList: []
    }
  },
  created() {
    console.log(this.row)
    this.getList()
  },
  methods: {
    resetTemp() {
      this.temp = {
        ID: '',
        applicationID: '',
        organizationID: '',
        stationID: '',
        customerOrganizationID: '',
        satelliteID: '',
        name: '',
        shortName: '',
        description: '',
        orderSeq: '',
        beginDate: '',
        endDate: '',
        distance: '',
        upSkyLoss: '',
        upAtmosphereLoss: '',
        downSkyLoss: '',
        dowmAtmosphereLoss: ''
      }
    },
    LoadSatelliteList() {
      getSatelliteList(
        'applicationID=' + this.row.applicationID +
        ',organizationID=' + this.row.organizationID
      ).then(response => {
        this.satelliteList = response.body.data.rows
      })
    },
    // 加载列表
    getList() {
      this.listLoading = true
      getStationSatelliteList('applicationID=' + this.row.applicationID +
        ',organizationID=' + this.row.organizationID +
        ',stationID=' + this.row.ID,
        'satellite.satelliteID.name,' +
        'distance,' +
        'upSkyLoss,' +
        'upAtmosphereLoss,' +
        'downSkyLoss,' +
        'dowmAtmosphereLoss,' +
        'shortName,' +
        'orderSeq'
      ).then((response) => {
        this.list = response.body.data.rows
        if (this.list.length > 0) {
          this.oldList = this.list.map(v => v.ID)
          this.newList = this.oldList.slice()
          this.temp.orderSeq = this.list[this.list.length - 1].orderSeq
        }
        this.listLoading = false
        this.$nextTick(() => {
          this.setSort()
        })
      })
      getSentenceList('code=distance', 'contentFormat').then((response) => {
        const sentence = response.body.data.rows
        if (sentence.length > 0) {
          this.distanceSentence = sentence[0].contentFormat
        }
      })
    },
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)

          // for show the changes, you can delete in you code
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
          const ids = this.newList.map(item => item).join()
          const params = { token: getToken(), ids: ids, functionID: global.functionID }
          batchSortStationSatellite(params).then(response => {
            if (response.header.code === 0) {
              this.getList()
              // this.$notify({ title: '批量排序成功', message: '批量排序成功', duration: global.notify.durationShort })
            } else {
              this.$notify({ title: '批量排序失败', message: response.header.msg, type: 'error', duration: global.notify.duration })
            }
          }).catch(err => {
            console.error(err)
          })
          console.log(this.newList)
        }
      })
    },
    // 创建
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loadingBtn = true // 提交按钮不可用
          this.loadingBtnTitle = '提交中...'
          let params = ''
          params += 'name=' + zEnBase64(this.row.name)
          if (isNotEmpty(this.row.applicationID)) { params += ',applicationID=' + zEnBase64(this.row.applicationID) }
          if (isNotEmpty(this.row.organizationID)) { params += ',organizationID=' + zEnBase64(this.row.organizationID) }
          if (isNotEmpty(this.row.ID)) { params += ',stationID=' + zEnBase64(this.row.ID) }
          // if (isNotEmpty(this.temp.customerOrganizationID)) { params += ',customerOrganizationID=' + zEnBase64(this.temp.customerOrganizationID) }
          // if (isNotEmpty(this.temp.description)) { params += ',description=' + zEnBase64(this.temp.description) }
          if (isNotEmpty(this.temp.orderSeq)) { params += ',orderSeq=' + zEnBase64(++this.temp.orderSeq) }
          // if (isNotEmpty(this.temp.beginDate)) { params += ',beginDate=' + zEnBase64(this.temp.beginDate) }
          // if (isNotEmpty(this.temp.endDate)) { params += ',endDate=' + zEnBase64(this.temp.endDate) }
          if (isNotEmpty(this.temp.distance)) { params += ',distance=' + zEnBase64(this.temp.distance) }
          if (isNotEmpty(this.temp.upSkyLoss)) { params += ',upSkyLoss=' + zEnBase64(this.temp.upSkyLoss) }
          if (isNotEmpty(this.temp.upAtmosphereLoss)) { params += ',upAtmosphereLoss=' + zEnBase64(this.temp.upAtmosphereLoss) }
          if (isNotEmpty(this.temp.downSkyLoss)) { params += ',downSkyLoss=' + zEnBase64(this.temp.downSkyLoss) }
          if (isNotEmpty(this.temp.dowmAtmosphereLoss)) { params += ',dowmAtmosphereLoss=' + zEnBase64(this.temp.dowmAtmosphereLoss) }
          params += ',satelliteID=' + zEnBase64(this.temp.satelliteID)
          fetchSatelliteOne({ token: getToken(), ID: this.temp.satelliteID }).then(response => {
            params += ',shortName=' + zEnBase64(response.body.data.name)
            const data = { token: getToken(), parameterArray: params }
            createStationSatellite(data).then(response => {
              if (response.header.code === 0) {
                this.getList()
                this.dialogFormVisible = false // 关闭对话框
                // this.$notify({ title: '创建成功', message: this.temp.shortName, type: 'success', duration: global.notify.durationShort })
                this.resetTemp()
                this.LoadSatelliteList()
              } else {
                this.loadingBtn = false // 提交按钮可用
                this.loadingBtnTitle = '确定'
                this.$notify({ title: '创建失败', message: response.header.msg, type: 'error', duration: global.notify.duration })
              }
            }).catch(err => {
              this.loadingBtn = false // 提交按钮可用
              this.loadingBtnTitle = '确定'
              console.error(err)
            })
          })
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('是否确认删除 ' + row.shortName + '?', {
        type: 'warning',
        closeOnClickModal: false, // 点击区域外不可关闭
        closeOnPressEscape: false // 按ESC不可关闭
      }).then(() => {
        const params = { token: getToken(), parameterArray: 'ID=' + row.ID, functionID: global.functionID }
        deleteStationSatellite(params).then(response => {
          if (response.header.code === 0) {
            this.getList()
            // this.$notify({ title: '删除成功', message: row.name, type: 'success', duration: global.notify.durationShort })
          } else {
            this.$notify({ title: '删除失败', message: response.header.msg, type: 'error', duration: global.notify.duration })
          }
        }).catch(err => {
          console.error(err)
        })
      })
    },
    // 显示编辑对话框，获取当前点击记录的信息
    handleUpdate(row) {
      this.LoadSatelliteList()
      this.loadingBtn = false // 提交按钮可用
      this.loadingBtnTitle = '确定'
      const params = { token: getToken(), ID: row.ID, functionID: global.functionID }
      fetchStationSatelliteOne(params).then(response => {
        if (response.header.code === 0) {
          this.temp = response.body.data
          this.dialogStatus = 'update'
          // this.dialogFormVisible = true // 显示对话框
          this.loadingBtn = false // 提交按钮可用
          getUserList('applicationID=' + this.temp.applicationID
          ).then(response => {
            this.userList = response.body.data.rows
          })
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        } else {
          this.$notify({ title: '获取数据失败', message: response.header.msg, type: 'error', duration: global.notify.duration })
        }
      }).catch(err => {
        console.error(err)
      })
    },
    // 编辑
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.loadingBtn = true // 提交按钮不可用
          this.loadingBtnTitle = '提交中...'
          let params = ''
          params += 'ID=' + this.temp.ID
          params += ',name=' + zEnBase64(this.temp.name)
          if (isNotEmpty(this.temp.applicationID)) { params += ',applicationID=' + zEnBase64(this.temp.applicationID) }
          if (isNotEmpty(this.temp.organizationID)) { params += ',organizationID=' + zEnBase64(this.temp.organizationID) }
          if (isNotEmpty(this.temp.stationID)) { params += ',stationID=' + zEnBase64(this.temp.stationID) }
          if (isNotEmpty(this.temp.customerOrganizationID)) { params += ',customerOrganizationID=' + zEnBase64(this.temp.customerOrganizationID) }
          if (isNotEmpty(this.temp.satelliteID)) { params += ',satelliteID=' + zEnBase64(this.temp.satelliteID) }
          if (isNotEmpty(this.temp.shortName)) { params += ',shortName=' + zEnBase64(this.temp.shortName) }
          if (isNotEmpty(this.temp.description)) { params += ',description=' + zEnBase64(this.temp.description) }
          if (isNotEmpty(this.temp.orderSeq)) { params += ',orderSeq=' + zEnBase64(this.temp.orderSeq) }
          // if (isNotEmpty(this.temp.beginDate)) { params += ',beginDate=' + zEnBase64(this.temp.beginDate) }
          // if (isNotEmpty(this.temp.endDate)) { params += ',endDate=' + zEnBase64(this.temp.endDate) }
          if (isNotEmpty(this.temp.distance)) { params += ',distance=' + zEnBase64(this.temp.distance) }
          if (isNotEmpty(this.temp.upSkyLoss)) { params += ',upSkyLoss=' + zEnBase64(this.temp.upSkyLoss) }
          if (isNotEmpty(this.temp.upAtmosphereLoss)) { params += ',upAtmosphereLoss=' + zEnBase64(this.temp.upAtmosphereLoss) }
          if (isNotEmpty(this.temp.downSkyLoss)) { params += ',downSkyLoss=' + zEnBase64(this.temp.downSkyLoss) }
          if (isNotEmpty(this.temp.dowmAtmosphereLoss)) { params += ',dowmAtmosphereLoss=' + zEnBase64(this.temp.dowmAtmosphereLoss) }
          const data = { token: getToken(), parameterArray: params, functionID: global.functionID }
          updateStationSatellite(data).then(response => {
            if (response.header.code === 0) {
              this.getList()
              // this.dialogFormVisible = false
              this.dialogStatus = 'create'
              this.resetTemp()
              this.LoadSatelliteList()
              // this.$notify({ title: '更新成功', message: this.temp.name, type: 'success', duration: global.notify.durationShort })
            } else {
              this.loadingBtn = false // 提交按钮可用
              this.loadingBtnTitle = '确定'
              this.$notify({ title: '更新失败', message: response.header.msg, type: 'error', duration: global.notify.duration })
            }
          }).catch(err => {
            this.loadingBtn = false // 提交按钮可用
            this.loadingBtnTitle = '确定'
            console.error(err)
          })
        }
      })
    },
    handleCancel() {
      this.resetTemp()
      this.dialogStatus = 'create'
    },
    closeDlg() {
      this.visible = false
      this.$parent.stationSatelliteVisible = false
    },
    common_event(event_name, index) {
      if (isNotEmpty(event_name)) {
        this[event_name](index)
      }
    },
    countDistance() {
      if (isNotEmpty(this.temp.satelliteID)) {
        let stationID = this.row.ID
        if (this.dialogStatus === 'update') {
          stationID = this.temp.stationID
        }
        doFormula({
          token: getToken(),
          mathematicalFormula: this.distanceSentence,
          parameterIDArray: 'stationID=' + stationID +
            ',satellite=' + this.temp.satelliteID
        }).then(response => {
          this.temp.distance = response.body.calculationResult.toFixed(2)
        })
      }
    }
  }
}
</script>

<style>
  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
  .sortable-ghost{
    opacity: .8;
    color: #fff!important;
    background: #42b983!important;
  }
</style>

<style scoped>
  .icon-star{
    margin-right:2px;
  }
  .drag-handler{
    width: 20px;
    height: 20px;
    cursor: pointer;
  }
  .show-d{
    margin-top: 15px;
  }
</style>
